<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { format } from 'date-fns'; // 用于格式化日期
import { selectAllApi, selectByIdApi, deleteGroupApi, deleteApi, insertApi, updateApi } from '@/api/courseCommunication.js'

// 查询条件
const searchCourseId = ref('');

// 表格数据
const tableData = ref([]);
const multipleSelection = ref([]);
const loading = ref(false); // 加载状态

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增交流');
const formData = ref({
  id: null,
  courseId: '',
  userId: '',
  content: '',
  createTime: '',
  courseName: '',
  userName: ''
});
const formRules = {
  courseId: [{ required: true, message: '请输入课程编号', trigger: 'blur' }],
  userId: [{ required: true, message: '请输入用户编号', trigger: 'blur' }],
  content: [
    { required: true, message: '请输入交流内容', trigger: 'blur' },
    { min: 5, max: 500, message: '交流内容长度在 5 到 500 个字符', trigger: 'blur' },
  ],
  createTime: [{ required: true, message: '请选择交流时间', trigger: 'change' }],
};

// 数据获取
onMounted(() => {
  fetchData();
});

// 获取表格数据
const fetchData = async () => {
  loading.value = true;
  try {
    //获取分页数据
    const res = await selectAllApi({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    if (res.code === 200) {
      tableData.value = res.data.list
        .filter(item => item.isDeleted === 0)
        .map(item => ({
          ...item,
          createTime: format(item.createTime, 'yyyy-MM-dd HH:mm:ss'),
        }));
      total.value = res.data.total;
    } else {
      console.error("查询失败：", res.data.msg);
    }
  }catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 根据课程编号查询
const handleSearch = async () => {
  try {
    //获取分页数据
    if (searchCourseId.value === '') {
      await fetchData();
      return;
    }
    const res = await selectByIdApi({
      id: searchCourseId.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    if (res.code === 200) {
      tableData.value = res.data.list
        .filter(item => item.isDeleted === 0)
        .map(item => ({
          ...item,
          createTime: format(item.createTime, 'yyyy-MM-dd HH:mm:ss'),
        }));
      total.value = res.data.total;
      ElMessage.success('搜索成功');
    } else {
      console.error("查询失败：", res.data.msg);
    }
  } catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  }
};

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.id);
};

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除选中的评论吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    loading.value = true;
    const reviewIds = multipleSelection.value;// 假设是 [1, 2, 3]
    const res = await deleteGroupApi(reviewIds);
    if (res.code === 200) {
      ElMessage.success("批量删除成功");
      await fetchData(); // 刷新数据
    } else {
      ElMessage.error(res.data.msg || "批量删除失败");
    }
  } catch(error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("批量删除错误:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 单条删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除交流 ${row.id} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      //调用删除接口
      await deleteApi(row.id);
      ElMessage.success(`删除交流 ID ${row.id} 成功`);
      await fetchData();
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增交流';
  formData.value = {
    id: null,
    courseId: '',
    userId: '',
    content: '',
    createTime: '',
    courseName: '',
    userName: ''
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑交流';
  formData.value = {
    ...row,
    createTime: row.createTime, // 时间格式已为字符串
  };
  dialogVisible.value = true;
};

// 提交表单（新增或编辑）
const handleSubmit = async () => {
  // 调用新增或编辑接口
  if (formData.value.id) {
    // 编辑
    await updateApi(formData.value);
    ElMessage.success(`编辑交流 ID ${formData.value.id} 成功`);
  } else {
    // 新增
    await insertApi(formData.value);
    ElMessage.success(`新增交流成功`);
  }
  dialogVisible.value = false;
  await fetchData();
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  fetchData();
};
</script>

<template>
  <div class="page-content">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchCourseId"
        placeholder="请输入课程编号"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增交流</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除交流</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      :loading="loading"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="courseId" label="课程编号" width="120" />
      <el-table-column prop="courseName" label="课程名称" width="120" />
      <el-table-column prop="userId" label="用户编号" width="120" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="content" label="交流内容" width="400" />
      <el-table-column prop="createTime" label="交流时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑交流</el-button>
          <el-button type="text" style="color: #f56c6c;" @click="handleDelete(row)">删除交流</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; justify-content: flex-end;"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 对话框（新增/编辑复用） -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="40%"
      :before-close="() => dialogVisible = false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程编号" prop="courseId">
              <el-input v-model="formData.courseId" placeholder="请输入课程编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户编号" prop="userId">
              <el-input v-model="formData.userId" placeholder="请输入用户编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="交流内容" prop="content">
          <el-input v-model="formData.content" type="textarea" :rows="3" placeholder="请输入交流内容" />
        </el-form-item>
        <el-form-item label="交流时间" prop="createTime">
          <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            placeholder="选择交流时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="date => date > new Date()"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-content {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-button {
  border-radius: 8px;
}

.el-button--primary {
  background: linear-gradient(90deg, #409eff, #79bbff);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(90deg, #337ecc, #66aaff);
}

.el-button--success {
  background: linear-gradient(90deg, #67c23a, #95d475);
  border: none;
}

.el-button--success:hover {
  background: linear-gradient(90deg, #5daf34, #85c265);
}

.el-button--danger {
  background: linear-gradient(90deg, #f56c6c, #ff9999);
  border: none;
}

.el-button--danger:hover {
  background: linear-gradient(90deg, #e65a5a, #ff8888);
}

.el-table tbody tr:hover > td {
  background-color: #f5f7fa;
}
.el-table__cell {
  padding: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
